package com.osdp.auth.server.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.osdp.auth.server.IUserService;
import com.osdp.common.constant.CommonConstant;
import com.osdp.sc.api.IPermissionApi;
import com.osdp.sc.api.IRoleApi;
import com.osdp.sc.dto.PermissionDTO;
import com.osdp.sc.api.ITenantUserApi;
import com.osdp.uc.api.IUserApi;
import com.osdp.sc.api.IRoleUserApi;
import com.osdp.sc.dto.TenantUserDTO;
import com.osdp.uc.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserApi userApi;

    @Autowired
    private IRoleApi roleApi;

    @Autowired
    private IRoleUserApi userRoleApi;

    @Autowired
    private ITenantUserApi tenantUserApi;

    @Autowired
    private IPermissionApi permissionApi;


    @Override
    public UserDTO queryUserByUserName(String userName) {
        return userApi.queryUserByUserName(userName);
    }


    @Override
    public List<String> queryRoleIdByUserId(String userId) {
        return userRoleApi.queryRoleIdByUserId(userId);
    }


    @Override
    public List<TenantUserDTO> queryTenantByUserId(String userId) {
        return tenantUserApi.queryTenantByUserId(userId);
    }

    @Override
    public String getCurrentTenantId(List<TenantUserDTO> tenants, String tenantCode) {
        return tenantUserApi.getCurrentTenantId(tenants,tenantCode);
    }

    /**
     * 获取租户id数组
     *
     * @param tenants
     * @return
     */
    @Override
    public List<String> getTenantIds(List<TenantUserDTO> tenants) {
        if (CollectionUtils.isEmpty(tenants)) {
            return Collections.emptyList();
        }
        return tenants.stream().map(t -> t.getTenantId()).collect(Collectors.toList());
    }

    @Override
    public List<String> getRoleCodeByUserId(String userId) {
        return roleApi.getRoleCodeByUserId(userId);
    }

    @Override
    public boolean hasSuperAdmin(List<String> roleCodes){
        if (CollectionUtils.isEmpty(roleCodes)) {
            return false;
        }
        return roleCodes.contains(CommonConstant.SUPER_TENANT_ADMIN);
    }

    @Override
    public List<PermissionDTO> queryPermissionButtonByUserId(String userId) {
        return permissionApi.queryPermissionButtonByUserId(userId);
    }

    @Override
    public List<PermissionDTO> queryPermissionAPIByUserId(String userId) {
        return permissionApi.queryPermissionAPIByUserId(userId);
    }

    @Override
    public Optional<List<PermissionDTO>> queryPermsButtonAndAPIByRoleCode(Set<String> roleCodes, String tenantId){
        return permissionApi.queryPermsButtonAndAPIByRoleCode(roleCodes,tenantId);
    }
}
